package com.conversationboard.authenticator;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthenticationCookie {

	public static String getUserName(HttpServletRequest request) throws IOException {

		Cookie[] cookies = request.getCookies();

		String userName = null;

		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equalsIgnoreCase("username")) {
					userName = cookie.getValue();
				}
			}
		}

		return Obfuscator.decrypt(userName);

	}


	public static String getPassword(HttpServletRequest request) throws IOException {

		Cookie[] cookies = request.getCookies();

		String password = null;

		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equalsIgnoreCase("password")) {
					password = cookie.getValue();
				}
			}
		}

		return Obfuscator.decrypt(password);

	}


	public static void storeCookie(String userName, String password, HttpServletRequest request, HttpServletResponse response) {

		userName = Obfuscator.encrypt(userName);
		password = Obfuscator.encrypt(password);

		Cookie userNameCookie = new Cookie("username", "\"" + userName + "\"");
		Cookie passwordCookie = new Cookie("password", "\"" + password + "\"");

		userNameCookie.setMaxAge(2000000000);
		passwordCookie.setMaxAge(2000000000);

		userNameCookie.setPath(request.getContextPath());
		passwordCookie.setPath(request.getContextPath());

		response.addCookie(userNameCookie);
		response.addCookie(passwordCookie);
	}


	public static void removeCookies(HttpServletRequest request, HttpServletResponse response) {

		Cookie userNameCookie = new Cookie("username", "");
		Cookie passwordCookie = new Cookie("password", "");

		userNameCookie.setMaxAge(0);
		passwordCookie.setMaxAge(0);

		userNameCookie.setPath(request.getContextPath());
		passwordCookie.setPath(request.getContextPath());

		response.addCookie(userNameCookie);
		response.addCookie(passwordCookie);

	}

}
